"use strict";
////////////全局变量//////////////\
var exercises = [];//欲创建的习题
var oldExercises = [];//已创建习题
var labDatas = [];//已上传文档
var LabID, LessonID;
LabID = getLessonIdFromUrl();
LessonID = getLessonIdFromUrl(1);
function getLessonIdFromUrl(op) {
    var url = decodeURI(location.href);
    var urlParmListStr = url.substr(url.indexOf('?') + 1, url.length);
    var theid = urlParmListStr.split("=")[1].split("&")[0];
    var lessonid = urlParmListStr.split("=")[2];
    if (op) {
        return lessonid;
    }
    return theid;
}
// 设置父页面iframe高度
function setParentHeight() {
    // 子页面设置父页面iframe高度
    if (window.parent.setcourseexciseIframeheight) {
        var ht = $("#container").height();
        ht = ht > 100 ? ht : 100;
        window.parent.setcourseexciseIframeheight(ht);
    }
}
$(function () {
    getLabInfo();
    //  getDataAndDoc();
});
function getLabInfo() {
    var url = "lessons/" + LessonID + "/labs/" + LabID;
    $.ajax({
        url: url,
        type: "GET",

        dataType: "json",
        success: function (data) {
            if (data) {
                //success

                fillLabInfo(data);

            }
            else {
                layer.msg(langThis("lab_queryIFail"));
            }
        },
        error: function (event) {
            layer.msg(langThis("lab_queryIFail"));
        }
    });
}
function getDataAndDoc() {
    $.ajax({
        url: "work_query.action",
        type: "POST",
        data: { "query_id": LabID },
        dataType: "json",
        success: function (data) {
            if (data.succeed == "true") {
                //success

                fillDataAndDoc(data.data);

            }
            else {
                layer.msg(langThis("lab_queryDFail"));
            }
        },
        error: function (event) {
            layer.msg(langThis("lab_queryDFail"));
        }
    });
}
function fillLabInfo(data) {
    $("#labName").val(data.name);
    $("#labdescribe").val(data.description);
    $("#labScore").val(data.score)
    // if(data.lab_type_id==1){
    //     var newOption=$("<option>").val(data.lab_type_id).text(langThis("lab_type_desktop"));
    //         $("#labType").append(newOption);
    // }
    // else{
    fillDataAndDoc(data.labresources)
    webTypeStep();
    // var newOption=$("<option>").val(data.lab_type_id).text(langThis("lab_type_online"));
    //     $("#labType").append(newOption);
    // }
    setParentHeight();
}
function webTypeStep() {
    $("#li_step3").hide();
    $("#li_step2").css("width", "initial");
    $("#li_step1").css("width", "86%");
    //   $("#step2SubmitBtn").val(langThis("pm_creat"));
}
function fillDataAndDoc(fileArr) {
    for (var i in fileArr) {
        var thefile = fileArr[i];

        if (thefile.type == "doc") {//doc
            fillUploadedDoc(thefile.id, thefile.name);
        }
        else if(thefile.type == "video"){//data
            fillUploadedVideo(thefile.id, thefile.name);
        }else{
            fillUploadedData(thefile.id, thefile.name);
        }
    }
}
function step1Click() {
    var target = $("#li_step1");
    if (target.hasClass("disabled")) {
        return;
    }
    target.children("hr").removeClass("greenHr");
    target.children("a").tab("show");
    var target2 = target.next();
    target2.children("img").attr("src", "imgs/时间轴－2-当前.png");
    target2.children('a').css('color', '#B7B7B7');
    target2.children('hr').removeClass("blueHr");
}

function step2Click() {
    var target = $("#li_step2");
    target.children('a').css('color', '#28bdff').tab('show');



}
function gotoStep2() {
    var labName = $("#labName").val();
    var labInfo = $("#labdescribe").val();
    if (labName == "" || labInfo == "") {
        layer.msg(langThis("nav_notEmpty"));
        return;
    }
    var labScore = $("#labScore").val();
    if (isNaN(labScore)) {
        layer.msg(langThis("st_scoreIsNum"));
        return;
    }
    var dateSeq = getFormartDate();

    var url = "lessons/" + LessonID + "/labs/" + LabID;
    var param = {
        name: labName,
        description: labInfo,
        score: labScore,
        lessonid: LessonID,
        larids: labDatas,
        seq: dateSeq
    };
    $.ajax({
        url: url,
        type: "PUT",
        data: JSON.stringify(param),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data) {
                //success

                layer.msg(langThis("myinfo_changeSuceess"));
                // step2Click();

            }
            else {
                layer.msg(langThis("lab_addInfoFail"));
            }
        },
        error: function (event) {
            layer.msg(langThis("lab_addInfoFail"));
        }
    });

}
function step2_upload_data() {
    var workspace_name = $("#labmethdName").val();
    var re = /#|\$|\%|\*|\?/;
    if (re.test(workspace_name)) {
        layer.msg(langThis("lb_filenamenot"));
        returrn;
    }
    var fileName = document.getElementById("labfile_workspace").value;
    if (workspace_name == "" || workspace_name == undefined) {
        layer.msg(langThis("lab_dataEmpty"));
        return;
    }
    if (fileName == undefined || fileName == "") {
        layer.msg(langThis("pm_choosefile"));
        return;
    }
    var rightFileType = fileName.slice(fileName.length - 4, fileName.length);
    if (rightFileType != ".zip" && rightFileType != ".rar") {
        layer.msg(langThis("lab_onlyrarzip"));
        return;
    }
    var ss = {

        "name": workspace_name

    };
    var url = "lessons/" + LessonID + "/labs/datas";
    var files = ['labfile_workspace'];
    showUploadPercent();
    $.ajaxFileUpload(
        {
            url: url,//用于文件上传的服务器端请求地址
            secureuri: false,//一般设置为false
            type: 'post',
            fileElementId: files,//文件上传空间的id属性  <input type="file" id="file" name="file" />
            dataType: 'json',//返回值类型 一般设置为json
            data: ss,
            success: function (data, status)  //服务器成功响应处理函数
            {
                if (data) {
                    var workspaceId = data.id;
                    var workspaceName = data.name;
                    fillUploadedData(workspaceId, workspaceName);
                    $("#labmethdName").val("");
                }
                else {
                    layer.msg(data.message.info);
                }
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                layer.msg(data.message.info + "-----" + e);
            }
        }
    );
}
function step2_upload_doc() {
    var workspace_name = $("#labdataName").val();
    var re = /#|\$|\%|\*|\?/;
    if (re.test(workspace_name)) {
        layer.msg(langThis("lb_filenamenot"));
        returrn;
    }
    var fileName = document.getElementById("labfile_doc").value;
    if (workspace_name == "" || workspace_name == undefined) {
        layer.msg(langThis("lab_docEmpty"));
        return;
    }
    if (fileName == undefined || fileName == "") {
        layer.msg(langThis("pm_choosefile"));
        return;
    }
    /*
     var rightFileType=fileName.slice(fileName.length-4,fileName.length);
     if(rightFileType!=".zip"&&rightFileType!=".rar"){
     layer.msg(langThis("lab_onlyrarzip"));
     return;
     }
     */
    var ss = {

        "name": workspace_name

    };

    var files = ['labfile_doc'];
    showUploadPercent();
    var url = "lessons/" + LessonID + "/labs/docs";
    $.ajaxFileUpload(
        {
            url: url,//用于文件上传的服务器端请求地址
            secureuri: false,//一般设置为false
            type: 'post',
            fileElementId: files,//文件上传空间的id属性  <input type="file" id="file" name="file" />
            dataType: 'json',//返回值类型 一般设置为json
            data: ss,
            success: function (data, status)  //服务器成功响应处理函数
            {
                if (data) {
                    var workspaceId = data.id;
                    var workspaceName = data.name;

                    fillUploadedDoc(workspaceId, workspaceName);
                    $("#labdataName").val("");
                }
                else {
                    layer.msg(data.message.info);
                }
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                layer.msg(data.message.info + "-----" + e);
            }
        }
    );
}
function step2_upload_video() {
    var workspace_name = $("#labVideoName").val();
    var re = /#|\$|\%|\*|\?/;
    if (re.test(workspace_name)) {
        layer.msg(langThis("lb_filenamenot"));
        returrn;
    }
    var fileName = document.getElementById("labfile_video").value;
    if (workspace_name == "" || workspace_name == undefined) {
        layer.msg(langThis("lab_docEmpty"));
        return;
    }
    if (fileName == undefined || fileName == "" || !(/^http:\/\//.test(fileName)||/^https:\/\//.test(fileName)||/^<iframe/.test(fileName)||/^<embed/.test(fileName)) ) {
        layer.msg(langThis("lab_URLTips"));
        return;
    }else{
        if (/youku.com/.test(fileName)) {
            var vid = fileName.split("show/id_")[1];
            if (vid) {
                fileName=vid.split("==")[0]+"==";
            } else if(/^<iframe/.test(fileName)){
                var ivid = fileName.split("embed/")[1];
                if (ivid) {
                    fileName=ivid.split("==")[0]+"==";
                }
            }else{
                var vvid = fileName.split("sid/")[1];
                if (vvid) {
                    fileName=vvid.split("==")[0]+"==";
                }
            }
        }
    }
    // var rightFileType = fileName.slice(fileName.length - 4, fileName.length);
    // if (rightFileType != ".mp4") {
    //     layer.msg(langThis("cc_videoForm"));
    //     return;
    // }
    // var ss = {
    //     "name": workspace_name
    // };
    $.ajax({
        url: "./lessons/"+LessonID+"/labs/youkuvideos",
        type: "POST",
        data: JSON.stringify({
            name:workspace_name,
            url:fileName
        }),
        dataType: "json",
        contentType: "application/json",
        success: function (data) {
            // console.log(data);
            if (data) {
                fillUploadedVideo(data.id, data.name);
                $("#labVideoName").val("");
                $("#labfile_video").val("");
            }
            else {
                layer.msg(data.message.info);
                hideUploadPercent();
            }
        },
        error: function (event) {
            layer.msg(langThis("lab_addInfoFail"));
        }
    });

    // var files = ['labfile_video'];
    // var url = "lessons/" + LessonID + "/labs/videos";
    // showUploadPercent();
    // $.ajaxFileUpload(
    //     {
    //         url: url,//用于文件上传的服务器端请求地址
    //         secureuri: false,//一般设置为false
    //         type: 'post',
    //         fileElementId: files,//文件上传空间的id属性  <input type="file" id="file" name="file" />
    //         dataType: 'json',//返回值类型 一般设置为json
    //         data: ss,
    //         success: function (data, status)  //服务器成功响应处理函数
    //         {
    //             if (data) {
    //                 var workspaceId = data.id;
    //                 var workspaceName = data.name;
    //                 fillUploadedVideo(workspaceId, workspaceName);
    //                 $("#labVideoName").val("");
    //             }
    //             else {
    //                 layer.msg(data.message.info);
    //                 hideUploadPercent();
    //             }
    //         },
    //         error: function (data, status, e)//服务器响应失败处理函数
    //         {
    //             // layer.msg(data.message.info+"-----"+e);
    //             hideUploadPercent();
    //         }
    //     }
    // );
}
function saveAndReturn() {
    window.parent.hideSavebtn();
    window.location.href = "LabManager?q=" + getLessonIdFromUrl(true);
}
function fillUploadedDoc(id, name) {
    hideUploadPercent();
    var spant = "<span class=\"label label-info\" id='twsid_" + id + "' onclick='deleteLabUploadedDoc(this)'>" + name + "<span class=\"glyphicon glyphicon-remove spanDel\" aria-hidden=\"true\"></span></span>";
    $("#uploadedP_doc").append(spant);
    labDatas.push(id);
    setParentHeight();
}
function fillUploadedData(id, name) {
    hideUploadPercent();
    var spant = "<span class=\"label label-info\" id='twsid_" + id + "' onclick='deleteLabUploadedData(this)'>" + name + "<span class=\"glyphicon glyphicon-remove spanDel\" aria-hidden=\"true\"></span></span>";
    $("#uploadedP_data").append(spant);
    labDatas.push(id);
    setParentHeight();
}
function fillUploadedVideo(id, name) {
    hideUploadPercent();
    var spant = "<span class=\"label label-info\" id='twsid_" + id + "' onclick='deleteLabUploadedVideo(this)'>" + name + "<span class=\"glyphicon glyphicon-remove spanDel\" aria-hidden=\"true\"></span></span>";
    $("#uploadedP_vdo").append(spant);
    labDatas.push(id);
    setParentHeight();
}
function showUploadPercent() {
    $('#uploadPercentModal').modal({ show: true, backdrop: "static" });
}
function hideUploadPercent() {
    $('#uploadPercentModal').modal("hide");
}
function deleteLabUploadedData(e) {
    var tWorkSpaceID = e.id.split("_")[1];

    layer.confirm(langThis("lab_delConfirm"), {
        btn: [
            langThis("pm_confirm"),
            langThis("pm_cancle")
        ], title: langThis("lab_atten")
    }, function () {
        layer.closeAll();
        var url = "lessons/" + LessonID + "/labs/" + LabID + "/datas/" + tWorkSpaceID;
        //  $.ajax({
        //             url:url,
        //             type:"DELETE",

        //             dataType:"json",
        //             success:function(data){
        //                 //success

        //                 if(data){
        //                     $(e).remove();
        //                     layer.msg(langThis("pm_deleteSuc"));

        //                 }
        //                 else {
        //                     layer.msg(langThis("pm_deleteFail"));
        //                 }
        //             },
        //             error:function(event){
        //                 layer.msg(langThis("pm_deleteFail"));
        //             }
        //         });
        for (var i in labDatas) {
            if (labDatas[i] == tWorkSpaceID) {
                labDatas.splice(i, 1);//删除该id
                break;
            }
        }
        $(e).remove();
        layer.msg(langThis("pm_deleteSuc"));
    }, function () { layer.closeAll(); });



}
function deleteLabUploadedVideo(e) {
    var tWorkSpaceID = e.id.split("_")[1];
    layer.confirm(langThis("lab_delConfirm"), {
        btn: [
            langThis("pm_confirm"),
            langThis("pm_cancle")
        ], title: langThis("lab_atten")
    }, function () {
        layer.closeAll();
        var url = "lessons/" + LessonID + "/labs/" + LabID + "/videos/" + tWorkSpaceID;
        //   $.ajax({
        //     url:url,
        //     type:"DELETE",

        //     dataType:"json",
        //     success:function(data){
        //         //success

        //         if(data){
        //             $(e).remove();
        //             layer.msg(langThis("pm_deleteSuc"));

        //         }
        //         else {
        //             layer.msg(langThis("pm_deleteFail"));
        //         }
        //     },
        //     error:function(event){
        //         layer.msg(langThis("pm_deleteFail"));
        //     }
        // });
        for (var i in labDatas) {
            if (labDatas[i] == tWorkSpaceID) {
                labDatas.splice(i, 1);//删除该id
                break;
            }
        }
        $(e).remove();
        layer.msg(langThis("pm_deleteSuc"));

    }, function () { layer.closeAll(); });
}
function deleteLabUploadedDoc(e) {
    var tWorkSpaceID = e.id.split("_")[1];

    layer.confirm(langThis("lab_delConfirm"), {
        btn: [
            langThis("pm_confirm"),
            langThis("pm_cancle")
        ], title: langThis("lab_atten")
    }, function () {
        layer.closeAll();
        var url = "lessons/" + LessonID + "/labs/" + LabID + "/docs/" + tWorkSpaceID;
        //  $.ajax({
        //     url:url,
        //     type:"DELETE",

        //     dataType:"json",
        //     success:function(data){
        //         //success

        //         if(data){
        //             $(e).remove();
        //             layer.msg(langThis("pm_deleteSuc"));

        //         }
        //         else {
        //             layer.msg(langThis("pm_deleteFail"));
        //         }
        //     },
        //     error:function(event){
        //         layer.msg(langThis("pm_deleteFail"));
        //     }
        // });
        for (var i in labDatas) {
            if (labDatas[i] == tWorkSpaceID) {
                labDatas.splice(i, 1);//删除该id
                break;
            }
        }
        $(e).remove();
        layer.msg(langThis("pm_deleteSuc"));
    }, function () { layer.closeAll(); });




}
function dataFile(e) {
    var f = e.files[0].name;
    var defaultFileName = f.substring(0, f.lastIndexOf("."));
    $("#labmethdName").val(defaultFileName);
}
function docFile(e) {
    var f = e.files[0].name;
    var defaultFileName = f.substring(0, f.lastIndexOf("."));
    $("#labdataName").val(defaultFileName);
}
function videoFile(e) {
    var f = e.files[0].name;
    var defaultFileName = f.substring(0, f.lastIndexOf("."));
    $("#labVideoName").val(defaultFileName);
}